var express = require('express');
var router = express.Router();
const userService = require('../service/userService');
const jwt = require("jsonwebtoken");
const {secretKey} = require('../token');
const WxPay = require("wechatpay-node-v3");
const fs = require("fs");

var fetch = require('node-fetch');
const https = require("https");
const {base64_decode} = require('../utils/file.js');
const {generateOrderNumber,sha256withRSA} = require('../utils/util.js');
const { v4: uuidv4 } = require('uuid');
const httpsAgent = new https.Agent({rejectUnauthorized: false});


const APP_ID = 'wx457004f898a98ca0';
const SECRET = 'cca7178937814f2feba4260310a94e9f';
const MCH_ID = '1634812315';

const pay = new WxPay({
  appid: APP_ID,
  mchid: MCH_ID,
  publicKey: fs.readFileSync('./cert/apiclient_cert.pem'), // 公钥
  privateKey: fs.readFileSync('./cert/apiclient_key.pem'), // 秘钥
});
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send("callback('respond with a resource')");
});

router.post('/reg',async function(req,res){
  let {username,pwd} = req.body;
  console.log(username,pwd);
  let data = await userService.insert({username,pwd});
  res.send(data);
});

/**
 * @swagger
 * /users/login:
 *    post:
 *      tags:
 *      - users
 *      summary: 用户登录
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                username:          
 *                  type: string
 *                  description: 用户名
 *                pwd:    
 *                  type: string
 *                  description: 密码
 *            
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
router.post('/login',async function(req,res){
  let {username,pwd} = req.body;
  let data = await userService.findByUsernameAndPwd({username,pwd});
  if(data.length > 0){
    let menu;
    if(data[0].school){
      menu = [
        { label: "学生管理", key: "/manage/student" },
        { label: "聊天", key: "/manage/chat" },
      ];
    }else{
      menu = [
        { label: "班级管理", key: "/manage/class" },
        { label: "老师管理", key: "/manage/teacher" },
        { label: "统计", key: "/manage/total" },
        { label: "聊天", key: "/manage/chat" },
      ]
    }
    console.log("data:",data[0])
    let authToken = jwt.sign({data:{payload:data[0],menu}}, secretKey);
    // req.session.user = data[0];
    res.send({status:1,token:authToken});
    // res.send({status:1});
  }else{
    res.send({status:0});
  }
});

router.post('/usernameExist',async function(req,res){
  let {username} = req.body;
  let data = await userService.findByUsername(username);
  if(data.length > 0){
    res.send({status:0});
  }else{
    res.send({status:1});
  }
});

router.get('/weixinLogin',async function(req,res){
  let code = req.query.code;
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
  console.log("url",url);
  try{
    let fetchResult = await fetch(url,{
      agent: httpsAgent
      });
    let data = await fetchResult.json();
    console.log('data',url,data)
    if(!data.errcode){
      let user = await userService.findByUsername(data.openid);
      if(Object.keys(user).length > 0){
        res.send(user);
      }else{
        let newUser = await userService.insert({username:data.openid,pwd:''});
        res.send(newUser);
      }
    }else{
      res.send({});
    }
  }catch(e){
    console.log("error:",e);
    res.send({});
  }
  
});
router.post('/weixinDetail/:id', async function(req,res){
  let id = req.params.id;
  let {nickname,image} = req.body;

  let user = await userService.findById(id);
  if(image){
    let strUUID = uuidv4();
    // 把头像转存成文件
    base64_decode(image,"./public/images/"+strUUID+".jpeg");
    user.headImg = strUUID+".jpeg";
  }
  if(nickname){
    user.nickname = nickname;
  }
  await userService.update(user);
  res.send(user);
})

router.post('/weixinPay',async function(req,res){
  try{
    const {openid} = req.body;
    const url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
    const body = {
      appid:APP_ID,
      mchid:MCH_ID,
      description:"朗沃课堂",
      out_trade_no:generateOrderNumber(),
      notify_url:"https://baidd.info:3002/users/payResult",
      amount:{
        total:10,
        currency:"CNY"
      },
      payer:{
        openid
      }
    };
    
    const nonce_str = Math.random().toString(36).substring(2, 15);// 随机字符串
    const timestamp = parseInt(+new Date() / 1000 + '').toString(); // 时间戳 秒
    const sign_url = '/v3/pay/transactions/jsapi';

    // 获取签名
    const signature = pay.getSignature('POST', nonce_str, timestamp, sign_url, body);
    // 获取头部authorization 参数
    const authorization = pay.getAuthorization(nonce_str, timestamp, signature);

    const options = {
      method: "POST",
      agent: httpsAgent,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        Authorization: authorization
      },
      body: JSON.stringify(body)
    }

    let fetchResult = await fetch(url,options);
    let data = await fetchResult.json();

    res.send({
      status:1,
      nonce_str,
      timestamp,
      package:"prepay_id="+data.prepay_id,
      paySign:sha256withRSA(`${APP_ID}\n${timestamp}\n${nonce_str}\nprepay_id=${data.prepay_id}\n`)
    });
  }catch(e){
    console.log("支付错误：",e)
    res.send({status:0,message:e});
  }
});

router.post('/payResult',function(req,res){
  res.send("");
});


module.exports = router;
